package com.zillion.certificate.service.impl;

import com.zillion.certificate.domain.HealthCertificate;
import com.zillion.certificate.mapper.ExamCertificateMapper;
import com.zillion.certificate.service.IExamCertificateService;
import com.zillion.common.core.domain.AjaxResult;
import com.zillion.common.utils.DateUtils;
import com.zillion.common.utils.file.Base64Utils;
import com.zillion.health.domain.HealthEmployeeReserve;
import com.zillion.health.mapper.HealthEmployeeReserveMapper;
import com.zillion.health.service.impl.HealthEmployeeReserveServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;

import static com.zillion.common.config.ZillionConfig.getProfile;

@Service
public class ExamCertificateServiceImpl implements IExamCertificateService {

    private static final Logger log = LoggerFactory.getLogger(HealthEmployeeReserveServiceImpl.class);

    @Autowired
    private ExamCertificateMapper examCertificateMapper;

    @Autowired
    private HealthEmployeeReserveMapper healthEmployeeReserveMapper;

    /**
     * 新增体检健康证信息
     *
     * @param healthCertificate 体检健康证
     * @return 结果
     */
    @Override
    public AjaxResult insertExamCertificate(HealthCertificate healthCertificate) {
        log.info("开始处理体检结果数据: {}", healthCertificate);
        HealthEmployeeReserve reserve = getHealthEmployeeReserve(healthCertificate);

        // 在体检结果表中插入回传数据
        healthCertificate.setCreateTime(DateUtils.getNowDate());
        // 同时更新预约列表中的信息
        int updated = healthEmployeeReserveMapper.updateReserveData(reserve);

        // 插入体检结果信息表
        int insertRow = examCertificateMapper.insertExamCertificate(healthCertificate);
        if (updated > 0) {
            return AjaxResult.success("上传成功");
        } else {
            reserve.setReserveDate(healthCertificate.getRegDate());
            updated = healthEmployeeReserveMapper.updateReserveData(reserve);
            if (updated > 0) {
                return AjaxResult.success("上传成功");
            }else {
                return AjaxResult.error("上传失败，无成功上传的数据");
            }
        }
    }

    /**
     * 根据体检回传的体检结果数据获取要更新的预约信息
     *
     * @param healthCertificate 预约信息
     * @return 预约信息
     */
    private static HealthEmployeeReserve getHealthEmployeeReserve(HealthCertificate healthCertificate) {
        HealthEmployeeReserve reserve = new HealthEmployeeReserve();
        reserve.setName(healthCertificate.getName());//预约姓名
        reserve.setIdCard(healthCertificate.getIdCard());//身份证号码
        reserve.setReserveDate(healthCertificate.getReserveDate());// 预约日期
        reserve.setQualify(healthCertificate.getQualify());//体检合格
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取年份、月份、日
        int year = currentDate.getYear();
        int monthValue = currentDate.getMonthValue(); // 1-12
        int dayOfMonth = currentDate.getDayOfMonth(); // 1-31
        String savePath = getProfile() + "/upload/" + year + "/" + monthValue + "/" + dayOfMonth;
        // 创建文件夹（如果不存在）
        File file = new File(savePath);
        if (!file.exists()) {
            boolean success = file.mkdirs();
            if (!success) {
                log.error("创建目录失败: {}", file.getAbsolutePath());
                throw new RuntimeException("无法创建文件保存目录");
            }
        }
        // 头像名称
        String avatarFileName = "/avatar_" + healthCertificate.getIdCard() + ".png";
        // 保存服务器路径
        String avatarPath = savePath + avatarFileName;
        // 头像base64转图片保存路径到数据库
        Base64Utils.saveBase64AsImage(healthCertificate.getAvatar(), avatarPath);
        // 保存数据库路径
        reserve.setEmployeeAvatar("/profile/upload/" + year + "/" + monthValue + "/" + dayOfMonth + avatarFileName);

        // 体检结果图片名称
        String tjResultFileName = "/tj_result_" + healthCertificate.getIdCard() + ".png";
        // 保存服务器路径
        String tjResultPath = savePath + tjResultFileName;
        // 体检结果base64转图片保存路径到数据库
        Base64Utils.saveBase64AsImage(healthCertificate.getTjResult(), tjResultPath);
        // 保存数据库路径
        reserve.setTjResult("/profile/upload/" + year + "/" + monthValue + "/" + dayOfMonth + tjResultFileName);
        // 设置体检状态--已结束
        reserve.setTjStatus(2);
        log.info("组装的体检结果数据: {}", reserve);
        return reserve;
    }
}
